package com.example.birdfriends.controller;

import cn.hutool.core.io.FileTypeUtil;
import com.example.birdfriends.pojo.post.Post;
import com.example.birdfriends.pojo.post.PostFront;
import com.example.birdfriends.service.PostService;
import com.example.birdfriends.utils.convert.ConvertService;
import com.example.birdfriends.utils.files.FileService;
import com.example.birdfriends.utils.result.Result;
import com.mysql.cj.SimpleQuery;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.jnlp.ClipboardService;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/post/image")
public class PostImageController {
    @Autowired
    private PostService postService = null;
    @Autowired
    private ConvertService convertService = null;
    @Autowired
    private FileService fileService = null;
    @Autowired
    private Result result = null;

    @PostMapping("/delete")  // 删除图片：1.找到相应帖子，2.从帖子的images中取出响应的url
    public Map<String, Object> deleteImage(@RequestBody PostFront postFront) throws ParseException {
//        postFront.printPost();
        String deleteImage = postFront.getDeleteImage();
//        System.out.println("delete image: "+deleteImage);
        Long pid = postFront.getPid();
        Long curLoginUid = postFront.getCurLoginUid();
        String curPage = postFront.getCurPage();
        Post post1 = postService.findPostByPid(pid);  // 根据前端的postFront查找对应的post

        PostFront postFront1 = convertService.post2PostFront(post1, curLoginUid, curPage);
        List<String> images = postFront1.getImages();
        List<String> previewImages = postFront1.getPreviewImages();
        fileService.removeListElem(images, deleteImage);
        fileService.removeListElem(previewImages, deleteImage);
//        System.out.println("删除图片后的images："+postFront1.getImages());
//        System.out.println("删除图片后的preview images："+postFront1.getPreviewImages());

        Post post = convertService.postFront2Post(postFront1);  // 将postFront1转化成可以写入数据库的post
        int update = postService.updatePostByPid(post);
        // 因为此时的post是根据postFront1修改的，所以就不去数据库查询修改后的post并转化成postFront了，而是直接使用设置好的postFront1

        boolean success = update > 0;
        if(!success){
            return result.resultMap(false, "修改失败", null);
        }

        return result.resultMap(true, "修改成功", postFront1);
    }

    List<String> imageList = null;
    List<String> videoList = null;

    @PostMapping("/upload")  // 增加图片，插入照片墙：新增图片需要考虑（插入的图片已存在，不可插入）
    public String updateImages(MultipartFile file, Long pid) throws IOException, ParseException {
        InputStream stream = file.getInputStream();  // 获取文件输出流
        String type = FileTypeUtil.getType(stream);  // 获取文件类型
        List<String> imageTypes = fileService.imageTypes();
        List<String> videoTypes = fileService.videoTypes();

        // 检索出响应的images列表，让后将图片url拼接好插入images
        String originalFilename = file.getOriginalFilename();
        String imagePath = "D:/bf-files/springboot-upload/post-files/post-images/post-"+pid+"/";
        String videoPath = "D:/bf-files/springboot-upload/post-files/post-videos/post-"+pid +"/";
        File parentImageFolder = new File(imagePath);
        File parentVideoFolder = new File(videoPath);
        if(!parentImageFolder.exists()) parentImageFolder.mkdirs();
        if(!parentVideoFolder.exists()) parentVideoFolder.mkdirs();
        if(imageTypes.contains(type)){
            File saveFile = new File(imagePath + originalFilename);
            file.transferTo(saveFile);

            String filePath = "http://localhost:8888/post-files/post-images/post-"+pid+"/"+originalFilename;
            if(imageList == null) {
                imageList = new ArrayList<>();
                imageList.add(filePath);
            }else imageList.add(filePath);
        }else if(videoTypes.contains(type)){
            File saveFile = new File(videoPath + originalFilename);
            file.transferTo(saveFile);

            String filePath = "http://localhost:8888/post-files/post-videos/post-"+pid+"/"+originalFilename;
            if(videoList == null) {
                videoList = new ArrayList<>();
                videoList.add(filePath);
            }else videoList.add(filePath);
        }else {
            return "非法文件格式";
        }
        System.out.println("被添加的文件：" + originalFilename);

        // 将该postFront转化成post，再利用post修改对应的数据项
        post.setImages(convertService.list2String(this.imageList));
        post.setVideos(convertService.list2String(this.videoList));
        System.out.print("添加文件后的post：");post.printPost();

        postService.setImagesAndVideos(this.post);
        return "修改成功";
    }

    private Post post = null;

    @PostMapping("/addImage")
    public Map<String, Object> setCurPost(@RequestBody PostFront postFront){
        Long pid = postFront.getPid();
        this.post = postService.findPostByPid(pid);
        this.imageList = convertService.string2List(this.post.getImages());
        this.videoList = convertService.string2List(this.post.getVideos());

        return result.resultMap(true, "设置post信息成功", null);
    }
}
